/**
 * 0. Project	: com.dnbns.bodywater 프로젝트
 *
 * 1. FileName	: GraphActivity.java
 * 2. Package	: com.dnbns.bodywater
 * 3. 작성자		: 윤화현
 * 4. 작성일		: 2013. 11. 21. 오전 9:22:45
 * 5. Comment	: 
 */

package com.dnbns.bodywater;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart;
import org.achartengine.chart.LineChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.dnbns.lib.CodeUtil;
import com.dnbns.lib.RbPreference;

public class GraphActivity extends Activity {

    private Context mContext;
    
    private String mBackgroundColor = "#ffffff";
    private String mLabelcolor = "#000000";
    
    private int mYear;
    private int mMonth;
    private int mDrinkLimit;
    
    private Calendar cal;
	private String mToday;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_graph);

		init();
		initTop();
		settingChart();
	}

/**
 ***************************************************************
 * init
 ***************************************************************
 */

	private void init() {
		mContext = this;
		
		ImageView prev = (ImageView)findViewById(R.id.prev);
		ImageView next = (ImageView)findViewById(R.id.next);

		prev.setOnClickListener(OCL);
		next.setOnClickListener(OCL);

    	cal = Calendar.getInstance();
    	mYear = cal.get(Calendar.YEAR);
    	mMonth = (cal.get(Calendar.MONTH)+1);

		mToday = mYear+"-"+mMonth;
    	
    	//저장된 값 가져오기.
		RbPreference pref = new RbPreference(getApplicationContext());
		int mWeight = Integer.valueOf(pref.getValue("weight", ""));

    	this.mDrinkLimit = (int)(mWeight*2.2/2*30);
    	
    	//천자리 짜르기.
    	if(mDrinkLimit/100 != 0){
    		mDrinkLimit = (mDrinkLimit/100)*100;
    	}

	}
	
	private void initTop(){
		ImageView back = (ImageView)findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}
	

/**
 ***************************************************************
 * Method
 ***************************************************************
 */

	private void settingChart() {
		
    	mYear = cal.get(Calendar.YEAR);
    	mMonth = (cal.get(Calendar.MONTH)+1);

    	TextView year = (TextView)findViewById(R.id.year_txt);
    	TextView month = (TextView)findViewById(R.id.month_txt);
    	
    	year.setText(mYear+"");
    	month.setText(mMonth+"");
    	
		//LineChart
		String[] titles = new String[] { "기준량" };
		int[] colors = new int[] { Color.RED };
		PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE };
		
		List<double[]> x = new ArrayList<double[]>();
		double[] a = new double[31];
		for(int i=0; i<31; i++){
			a[i] = i+1;
		}
		x.add(a);
		
		//최대라인
		List<double[]> values = new ArrayList<double[]>();
		double[] limit = new double[31];
		for(int i=0; i<31; i++){
			limit[i] = mDrinkLimit;
		}
		values.add(limit);
		
		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
		
		renderer.setPointSize(5.5f);
		XYSeriesRenderer r = (XYSeriesRenderer) renderer.getSeriesRendererAt(0);
		r.setLineWidth(1);
		r.setFillPoints(true);
		r.setHighlighted(true);

		setChartSettings(renderer, mMonth+"월", "day", "ml", 0.5, 10.5, 0, mDrinkLimit+1000);

		//표시 간격
		renderer.setXLabels(12);
		renderer.setYLabels(5);
		renderer.setGridColor(Color.parseColor("#f3f3f3"));
		renderer.setShowGridX(true);
		//정렬방향
		renderer.setXLabelsAlign(Align.CENTER);
		renderer.setYLabelsAlign(Align.LEFT);
		renderer.setXLabelsColor(Color.parseColor(mLabelcolor));
		renderer.setYLabelsColor(0, Color.parseColor(mLabelcolor));
//		renderer.setZoomButtonsVisible(true);
		//스크롤여부
		renderer.setPanEnabled(true, false);
		renderer.setPanLimits(new double[] {0, 32, 0, mDrinkLimit+1000});
		//줌 여부
		renderer.setZoomEnabled(false, false);
		renderer.setZoomRate(1.1f);
		renderer.setBarSpacing(0.3f);
		
    	//차트값 초기화
		double[] dd = new double[31];
		for(int i=0; i < 31; i++){
			dd[i] = 0;
		}

		//DB에서 차크값 가져오기.
		JSONArray objA = CodeUtil.getInstance(mContext).getQuery("water_graph", ""+mYear, ""+mMonth);

		for(int i=0; i<objA.length(); i++){
			try {
				dd[objA.getJSONObject(i).getInt("day")] += objA.getJSONObject(i).getInt("cup_vol");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		XYSeries waterSeries = new XYSeries("내가먹는양");
		for(int i=0; i<31; i++){
			waterSeries.add((i+1), dd[i]);
		}
		renderer.setBarSpacing(0.3f);
		XYSeriesRenderer waterRenderer = new XYSeriesRenderer();
		waterRenderer.setColor(Color.argb(250, 0, 210, 250));

		XYMultipleSeriesDataset dataset = buildDataset(titles, x, values);
		dataset.addSeries(0, waterSeries);
		renderer.addSeriesRenderer(0, waterRenderer);
		waterRenderer.setDisplayChartValues(true);
		waterRenderer.setChartValuesTextSize(10);

		String[] types = new String[] { BarChart.TYPE, LineChart.TYPE };
		GraphicalView mGraphicalView = ChartFactory.getCombinedXYChartView(mContext, dataset, renderer, types);
		
		LinearLayout dynamicLayout = (LinearLayout) findViewById(R.id.graph_layout);
		dynamicLayout.removeAllViews();
		dynamicLayout.addView(mGraphicalView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}

    //Renderer 객체 생성및 각 값 지정.
	protected XYMultipleSeriesRenderer buildRenderer(int[] colors, PointStyle[] styles) {
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		setRenderer(renderer, colors, styles);
		return renderer;
	}

	protected void setRenderer(XYMultipleSeriesRenderer renderer, int[] colors, PointStyle[] styles) {
		// text사이즈 지정.
		renderer.setAxisTitleTextSize(20);		//X,Y축 제목
		renderer.setChartTitleTextSize(24);		//차트제목
		renderer.setLabelsTextSize(15);
		renderer.setLegendTextSize(15);
		renderer.setPointSize(5f);
		
		//생성하는 차트 값 지정.
		int length = colors.length;
		for (int i = 0; i < length; i++) {
			XYSeriesRenderer r = new XYSeriesRenderer();
			r.setColor(colors[i]);
			r.setPointStyle(styles[i]);
			renderer.addSeriesRenderer(r);
		}
	}

    //차트의 기본적인 셋팅.
	protected void setChartSettings(XYMultipleSeriesRenderer renderer,
			String title, String xTitle, String yTitle, double xMin,
			double xMax, double yMin, double yMax) {
		
		//마진 셋팅
		renderer.setMargins(new int[] {30, 30, 30, 30} );
		//Bg 칼러 셋팅
		renderer.setApplyBackgroundColor(true);
		renderer.setMarginsColor(Color.parseColor(mBackgroundColor));
		renderer.setBackgroundColor(Color.parseColor(mBackgroundColor));
		//제목 셋팅
		renderer.setChartTitle(title);	//차트제목		
		renderer.setXTitle(xTitle);		//X 타이틀
		renderer.setYTitle(yTitle);		//Y 타이틀
		//X, Y축 값 셋팅
		renderer.setXAxisMin(xMin);
		renderer.setXAxisMax(xMax);
		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);
		//Text 칼러 셋팅
		renderer.setAxesColor(Color.parseColor(mLabelcolor));
		renderer.setLabelsColor(Color.parseColor(mLabelcolor));
	}

    //Dataset 정리
	protected XYMultipleSeriesDataset buildDataset(String[] titles,
			List<double[]> xValues, List<double[]> yValues) {
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		addXYSeries(dataset, titles, xValues, yValues, 0);
		return dataset;
	}

	public void addXYSeries(XYMultipleSeriesDataset dataset, String[] titles,
			List<double[]> xValues, List<double[]> yValues, int scale) {
		int length = titles.length;
		for (int i = 0; i < length; i++) {
			XYSeries series = new XYSeries(titles[i], scale);
			double[] xV = xValues.get(i);
			double[] yV = yValues.get(i);
			int seriesLength = xV.length;
			for (int k = 0; k < seriesLength; k++) {
				series.add(xV[k], yV[k]);
			}
			dataset.addSeries(series);
		}
	}
	
/**
 ***************************************************************
 * Event
 ***************************************************************
 */

	private View.OnClickListener OCL = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.prev:
				cal.add(Calendar.MONTH, -1);
				settingChart();
				break;
			case R.id.next:
				if(mToday.equals(mYear+"-"+mMonth)){
					return;
				}else{
					cal.add(Calendar.MONTH, +1);
					settingChart();
				}
				break;
			}
		}
	};

	
}
